# encoding: utf-8 -*-
# Python3
# Author：xiang
# Time：2023-04-25 15:52

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders


def send_mail(result_info):
    # 发送邮件的基本信息
    smtp_server = "smtp.qq.com"  # 邮件服务器地址
    smtp_port = 465  # 邮件服务器端口号
    username = "290407387@qq.com"  # 发件人邮箱账号
    password = "onpwdbtqcdtocabh"  # 发件人邮箱密码
    sender = "290407387@qq.com"  # 发件人邮箱地址
    receiver = [email.strip() for email in result_info['casename'].split(';')]  # 收件人邮箱地址

    # 构建邮件内容
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = ','.join(receiver)
    msg['Subject'] = f"任务：【{result_info['casename']}】自动化测试结果邮件通知！"

    # 邮件正文
    script_dir = os.path.dirname(os.path.abspath(__file__))
    file_path = os.path.join(script_dir, 'email_template.html')
    with open(file_path, 'r', encoding='utf-8') as f:
        content_html = f.read()
        new_content = content_html.replace('${casename}', result_info['casename'])\
            .replace('${casecount}', str(result_info['casecount']))\
            .replace('${casesuc}', str(result_info['casesuc']))\
            .replace('${casefail}', str(result_info['casefail']))\
            .replace('${caseskip}', str(result_info['caseskip']))
    text = MIMEText(new_content, 'html', 'utf-8')

    # 邮件附件
    file_path = result_info['file_path']  # 附件文件名
    if file_path and os.path.exists(file_path):
        with open(file_path, 'rb') as f:
            attachment = MIMEBase('application', 'octet-stream')
            attachment.set_payload(f.read())
            encoders.encode_base64(attachment)
            attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_path))
            attachment.add_header('Content-Type', 'text/html')
            msg.attach(attachment)
    text = MIMEText(f"附件为【{result_info['casename']}】测试结果，如有异常请及时处理!")

    # 发送邮件
    msg.attach(text)
    with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
        server.login(username, password)
        server.sendmail(sender, receiver, msg.as_string())


if __name__ == '__main__':
    result_info = {
        "casename": ' 123@qq.com ; 456@qq.com ',
        "casecount": 1,
        "casesuc": 2,
        "casefail": 3,
        "caseskip": 4,
    }
    send_mail(result_info)
